<template>
  <div>
    <div class="title">
      保活推送管理<span>支持多种推送方式，包括广播、按用户、按应用、按昵称推送</span>
    </div>

    <!-- 推送方式选择 -->
    <div class="push-type-selector">
      <el-radio-group v-model="pushType" @change="handlePushTypeChange">
        <el-radio-button label="broadcast">广播推送</el-radio-button>
        <el-radio-button label="user">按用户ID推送</el-radio-button>
        <el-radio-button label="app">按应用推送</el-radio-button>
        <el-radio-button label="nickname">按昵称推送</el-radio-button>
      </el-radio-group>
    </div>

    <!-- 推送表单 -->
    <div class="content-box">
      <el-form ref="pushForm" class="form-box" :model="pushForm" :rules="rules" label-width="120px">
        <!-- 标题输入框 -->
        <el-form-item label="推送标题" prop="title">
          <el-input v-model="pushForm.title" placeholder="请输入推送标题" />
        </el-form-item>

        <!-- 内容输入框 -->
        <el-form-item label="推送内容" prop="content">
          <el-input v-model="pushForm.content" type="textarea" placeholder="请输入推送内容" :rows="4" />
        </el-form-item>

        <!-- URL输入框 -->
        <el-form-item label="跳转链接" prop="url">
          <el-input v-model="pushForm.url" placeholder="请输入跳转链接（可选）" />
        </el-form-item>

        <!-- 根据推送类型显示不同的输入框 -->
        <el-form-item v-if="pushType === 'user'" label="用户ID" prop="uid">
          <el-input v-model="pushForm.uid" placeholder="请输入目标用户ID" />
        </el-form-item>

        <el-form-item v-if="pushType === 'app'" label="应用名称" prop="appname">
          <el-select v-model="pushForm.appname" placeholder="请选择目标应用" style="width: 100%">
            <el-option label="310大师" value="310" />
            <el-option label="星球客" value="xqk" />
            <el-option label="有球体育" value="yqty" />
          </el-select>
        </el-form-item>

        <el-form-item v-if="pushType === 'nickname'" label="用户昵称" prop="nickname">
          <el-input v-model="pushForm.nickname" placeholder="请输入目标用户昵称" />
        </el-form-item>

        <!-- 推送按钮 -->
        <el-form-item>
          <el-button type="primary" :loading="pushLoading" @click="onSubmit">推送</el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 帮助按钮区域 -->
      <div class="select-box">
        <el-button v-for="item in helpList" :key="item.value" :type="item.type" @click="pushForm.url = item.value">
          {{ item.label }}
        </el-button>
      </div>
    </div>

    <!-- 在线用户信息 -->
    <div class="online-users-section">
      <div class="section-title">
        <span>在线用户信息</span>
        <el-button type="text" :loading="loadingOnlineUsers" @click="getOnlineUsers">刷新</el-button>
      </div>
      <el-table v-loading="loadingOnlineUsers" :data="onlineUsers" style="width: 100%">
        <el-table-column prop="userId" label="用户ID" width="120" />
        <el-table-column prop="appname" label="应用名称" width="120" />
        <el-table-column prop="nickname" label="昵称" width="120" />
        <el-table-column prop="connectTime" label="连接时间" width="180">
          <template slot-scope="scope">
            {{ formatTime(scope.row.connectTime) }}
          </template>
        </el-table-column>
      </el-table>
      <div class="online-count">
        当前在线用户数：{{ onlineUsers.length }}
      </div>
    </div>

    <!-- 推送历史记录 -->
    <div class="push-history-section">
      <div class="section-title">推送历史</div>
      <el-table :data="pushHistory" style="width: 100%">
        <el-table-column prop="type" label="推送类型" width="120">
          <template slot-scope="scope">
            <el-tag :type="getTypeTagType(scope.row.type)">{{ getTypeLabel(scope.row.type) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="title" label="标题" width="200" />
        <el-table-column prop="content" label="内容" show-overflow-tooltip />
        <el-table-column prop="target" label="目标" width="150" />
        <el-table-column prop="sent" label="推送范围" width="120">
          <template slot-scope="scope">
            <span v-if="scope.row.type === 'broadcast' || scope.row.type === 'app'">群推</span>
            <span v-else>{{ scope.row.sent }} 个用户</span>
          </template>
        </el-table-column>
        <el-table-column prop="time" label="推送时间" width="180">
          <template slot-scope="scope">
            {{ formatTime(scope.row.time) }}
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 手机模拟器 -->
    <div class="moni-ios">
      <img src="@/assets/pushImage/mock-phone.png" alt="">
      <div class="mock-box">
        <div class="mock-box-top">
          <img src="@/assets/310logo.png" alt="">
          <span>310大师</span>
        </div>
        <div class="mock-box-bottom">
          <span>{{ pushForm.title || '通知标题' }}</span>
          <span>{{ pushForm.content || '通知内容' }}</span>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import axios from 'axios'

export default {
  data() {
    return {
      pushType: 'broadcast', // 推送类型
      pushLoading: false,
      loadingOnlineUsers: false,
      onlineUsers: [],
      pushHistory: [],

      // 表单数据对象
      pushForm: {
        title: '',
        content: '',
        url: '',
        uid: '',
        appname: '',
        nickname: ''
      },

      // 帮助按钮列表
      helpList: [
        {
          label: '专家详情',
          value: '/pages/specialist/specialistInfo?type=1&id=请填写',
          type: 'success'
        },
        {
          label: '方案详情',
          value: '/pages/scheme/schemeInfo?id=请填写',
          type: 'warning'
        },
        {
          label: '赛事详情',
          value: '/pages/competition/competitionInfo?match_id=请填写',
          type: 'danger'
        }
      ],

      // 表单校验规则
      rules: {
        title: [
          { required: true, message: '请输入推送标题', trigger: 'blur' }
        ],
        content: [
          { required: true, message: '请输入推送内容', trigger: 'blur' }
        ],
        uid: [
          { required: true, message: '请输入用户ID', trigger: 'blur' }
        ],
        appname: [
          { required: true, message: '请输入应用名称', trigger: 'blur' }
        ],
        nickname: [
          { required: true, message: '请输入用户昵称', trigger: 'blur' }
        ]
      }
    }
  },

  mounted() {
    this.getOnlineUsers()
    this.loadPushHistory()
  },

  methods: {
    // 推送类型改变时的处理
    handlePushTypeChange(type) {
      // 清空相关字段
      this.pushForm.uid = ''
      this.pushForm.appname = ''
      this.pushForm.nickname = ''

      // 根据类型设置默认值
      if (type === 'app') {
        this.pushForm.appname = '310' // 默认选择310大师
      }
    },

    // 获取在线用户
    async getOnlineUsers() {
      this.loadingOnlineUsers = true
      try {
        const response = await axios.get('https://beforai.zctj16888.com/online-users')
        if (response.data.success) {
          this.onlineUsers = response.data.onlineUsers || []
        } else {
          this.$message.error('获取在线用户失败')
        }
      } catch (error) {
        console.error('获取在线用户失败:', error)
        this.$message.error('获取在线用户失败')
      } finally {
        this.loadingOnlineUsers = false
      }
    },

    // 加载推送历史
    loadPushHistory() {
      // 从localStorage加载推送历史
      const history = localStorage.getItem('pushHistory')
      if (history) {
        this.pushHistory = JSON.parse(history)
      }
    },

    // 保存推送历史
    savePushHistory(record) {
      this.pushHistory.unshift(record)
      // 只保留最近50条记录
      if (this.pushHistory.length > 50) {
        this.pushHistory = this.pushHistory.slice(0, 50)
      }
      localStorage.setItem('pushHistory', JSON.stringify(this.pushHistory))
    },

    // 推送消息
    async onSubmit() {
      this.$refs.pushForm.validate(async(valid) => {
        if (valid) {
          this.pushLoading = true

          try {
            let response
            const baseData = {
              title: this.pushForm.title,
              content: this.pushForm.content,
              url: this.pushForm.url
            }

            // 根据推送类型选择不同的API
            switch (this.pushType) {
              case 'broadcast':
                response = await axios.post('https://beforai.zctj16888.com/push', baseData)
                break
              case 'user':
                response = await axios.post('https://beforai.zctj16888.com/310push', {
                  ...baseData,
                  uid: this.pushForm.uid
                })
                break
              case 'app':
                response = await axios.post('https://beforai.zctj16888.com/push-by-app', {
                  ...baseData,
                  appname: this.pushForm.appname
                })
                break
              case 'nickname':
                response = await axios.post('https://beforai.zctj16888.com/push-by-nickname', {
                  ...baseData,
                  nickname: this.pushForm.nickname
                })
                break
            }

            if (response.data.success) {
              // 根据推送类型显示不同的成功消息
              if (this.pushType === 'broadcast' || this.pushType === 'app') {
                this.$message.success('群推成功')
              } else {
                this.$message.success(`推送成功，共推送 ${response.data.sent} 个用户`)
              }

              // 保存推送历史
              this.savePushHistory({
                type: this.pushType,
                title: this.pushForm.title,
                content: this.pushForm.content,
                target: this.getTargetInfo(),
                sent: (this.pushType === 'broadcast' || this.pushType === 'app') ? '群推' : response.data.sent,
                time: new Date().toISOString()
              })

              // 刷新在线用户
              this.getOnlineUsers()
            } else {
              this.$message.error('推送失败')
            }
          } catch (error) {
            console.error('推送失败:', error)
            this.$message.error('推送失败: ' + (error.response?.data?.error || error.message))
          } finally {
            this.pushLoading = false
          }
        } else {
          this.$message.error('请检查表单输入')
        }
      })
    },

    // 获取目标信息
    getTargetInfo() {
      switch (this.pushType) {
        case 'user':
          return `用户ID: ${this.pushForm.uid}`
        case 'app': {
          const appNameMap = {
            '310': '310大师',
            'xqk': '星球客',
            'yqty': '有球体育'
          }
          return `应用: ${appNameMap[this.pushForm.appname] || this.pushForm.appname}`
        }
        case 'nickname':
          return `昵称: ${this.pushForm.nickname}`
        default:
          return '所有用户'
      }
    },

    // 重置表单
    resetForm() {
      this.$refs.pushForm.resetFields()
      this.pushForm = {
        title: '',
        content: '',
        url: '',
        uid: '',
        appname: '',
        nickname: ''
      }
    },

    // 格式化时间
    formatTime(timeStr) {
      if (!timeStr) return '-'
      const date = new Date(timeStr)
      return date.toLocaleString('zh-CN')
    },

    // 获取类型标签类型
    getTypeTagType(type) {
      const typeMap = {
        'broadcast': 'success',
        'user': 'primary',
        'app': 'warning',
        'nickname': 'info'
      }
      return typeMap[type] || 'default'
    },

    // 获取类型标签文本
    getTypeLabel(type) {
      const typeMap = {
        'broadcast': '广播推送',
        'user': '按用户推送',
        'app': '按应用推送',
        'nickname': '按昵称推送'
      }
      return typeMap[type] || type
    }
  }
}
</script>

<style scoped>
.title {
    width: 100%;
    padding-left: 100px;
    padding-top: 50px;
    font-size: 25px;
    margin-bottom: 30px;
}

.title span {
    font-size: 12px;
    color: #666;
    margin-left: 10px;
}

.push-type-selector {
    width: 100%;
    padding: 0 100px 30px;
    text-align: center;
}

.content-box {
    width: 100%;
    display: flex;
    align-items: flex-start;
    padding: 0 100px;
}

.form-box {
    flex: 1;
    margin-right: 50px;
    max-width: 600px;
}

.select-box {
    display: flex;
    flex-direction: column;
    width: 250px;
    align-items: center;
}

.select-box > button {
    margin-bottom: 20px;
    margin-left: 0px;
    width: 180px;
}

.online-users-section,
.push-history-section {
    margin: 40px 100px;
    padding: 20px;
    background: #f8f9fa;
    border-radius: 8px;
}

.section-title {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    font-size: 18px;
    font-weight: bold;
    color: #333;
}

.online-count {
    margin-top: 15px;
    text-align: right;
    color: #666;
    font-size: 14px;
}

.moni-ios {
    margin-left: 100px;
    position: relative;
    margin-top: 40px;
}

.moni-ios > img {
    width: 200px;
    height: 384px;
}

.mock-box {
    width: 150px;
    background-color: #F5DDE1;
    position: absolute;
    z-index: 1;
    top: 120px;
    left: 15px;
    border-radius: 10px;
}

.mock-box-top {
    display: flex;
    align-items: center;
    width: 100%;
    font-size: 12px;
    margin-top: 10px;
}

.mock-box-bottom {
    display: flex;
    flex-direction: column;
    font-size: 13px;
    padding-left: 10px;
    margin-top: 4px;
    overflow: hidden;
    text-overflow: ellipsis;
    word-wrap: normal;
}

.mock-box-bottom span {
    overflow: hidden;
    text-overflow: ellipsis;
    word-wrap: none;
}

.mock-box-bottom span:nth-child(1) {
    font-weight: bold;
    margin-bottom: 1px;
}

.mock-box-top > img {
    width: 20px;
    height: 20px;
    border-radius: 6px;
    margin: 0px 5px 0px 10px;
}

/* 响应式设计 */
@media (max-width: 768px) {
    .content-box {
        flex-direction: column;
        padding: 0 20px;
    }

    .form-box {
        margin-right: 0;
        margin-bottom: 20px;
    }

    .online-users-section,
    .push-history-section {
        margin: 20px;
    }

    .title {
        padding-left: 20px;
    }

    .push-type-selector {
        padding: 0 20px 30px;
    }
}
</style>
